/* 
 *  javascribd - Java client library for the Scribd API. 
 *  Copyright (C) 2009 by Marcel Eyke, http://code.google.com/p/javascribd/ 
 *  Use is subject to license terms of LGPLv3. See license.txt. 
 */
package com.google.code.javascribd.connection;

import java.io.IOException;
import java.net.Proxy;

public class ScribdClient {
	private static final String DEFAULT_SCRIBD_API_URL = "http://api.scribd.com/api";

	private ScribdConnection connection;
	private ScribdResponseParser responseParser;

	public ScribdClient() {
		// set default properties
		this.connection = new SimpleConnection();
		this.responseParser = new JaxbResponseParser();
		this.setUrl(DEFAULT_SCRIBD_API_URL);
		this.setProxy(Proxy.NO_PROXY);
	}

	public void setConnection(ScribdConnection connection) {
		if (connection == null) {
			throw new IllegalArgumentException("connection must be not null");
		}
		ScribdConnection oldConnection = this.connection;
		this.connection = connection;
		assert this.connection != null;
		this.setProxy(oldConnection.getProxy());
		this.setUrl(oldConnection.getUrl());
	}

	public void setResponseParser(ScribdResponseParser responseParser) {
		if (connection == null) {
			throw new IllegalArgumentException("responseParser must be not null");
		}
		this.responseParser = responseParser;
	}

	public void setProxy(Proxy proxy) {
		this.checkHttpConnection();
		this.connection.setProxy(proxy);
	}

	public void setUrl(String apiUrl) {
		this.checkHttpConnection();
		this.connection.setUrl(apiUrl);
	}

	public <T extends ScribdResponse> T execute(ScribdMethod<T> method) throws ScribdConnectionException, IOException {
		if (method.hasPOSTParameters()) {
			return this.connection.postRequest(method, this.responseParser);
		} else {
			return this.connection.getRequest(method, this.responseParser);
		}
	}

	private void checkHttpConnection() {
		if (this.connection == null) {
			throw new IllegalStateException("httpConnection is null");
		}
	}
}
